package com.demo.jetpack.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

/**
 *    author : robert
 *    date   : 2021/8/11 13:23
 *    desc   :
 */
abstract class BaseFragment : Fragment() {
    protected var mView: View? = null
    private var isInited: Boolean = false
    protected lateinit var mContext: Context

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return mView ?: let { inflater.inflate(getLayout(), container, false) }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        mContext = this.requireContext()
        if (savedInstanceState == null) {
            if (!isHidden) {
                isInited = true
                initFreshData()
            }
        } else {
            if (!isHidden) {
                isInited = true
                initFreshData()
            }
        }
    }

    open fun initFreshData() {
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        onHiddenChange(hidden)
        if (!isInited && !hidden) {
            isInited = true
            initFreshData()
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        cancelRequest()
    }

    open fun initData() {}

    open fun cancelRequest() {}

    open fun onHiddenChange(hidden: Boolean) {}

    abstract fun getLayout(): Int

}